package app.android.sotaynauan;

import java.util.List;

import com.commonsware.cwac.loaderex.SQLiteCursorLoader;

import android.location.GpsStatus.Listener;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.IntentSender.OnFinished;
import android.content.Loader;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import app.android.customcontentprovider.FoodContentProvider;
import app.android.database.Constants;
import app.android.database.MyDatabaseAdapter;

public class MainActivity extends ListActivity implements
		LoaderManager.LoaderCallbacks<Cursor>, OnQueryTextListener,
		OnItemClickListener {
	private SearchView mSearchView;
	private static String QUERY_EXTRA_KEY = "QUERY_EXTRA_KEY";
	private SimpleCursorAdapter adapter;
	private MyDatabaseAdapter mDBAdapter;

	public static String DETAIL_ID = "DETAIL_ID";
	public static String FAVOURITE = "FAVOURITE";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_ACTION_BAR);				
		//setContentView(R.layout.activity_main);
		
		mDBAdapter = new MyDatabaseAdapter(MainActivity.this);
		mDBAdapter.open();		

		//ListView lv = (ListView) findViewById(R.id.lvFoods);
		ListView lv = getListView();
		
		// Create a new adapter and bind it to the List View
		String[] fromColumns = { Constants.FOOD_NAME };
		int[] toViews = { android.R.id.text1 }; // The TextView in
												// simple_list_item_1

		// Create an empty adapter we will use to display the loaded data.
		// We pass null for the cursor, then update it in onLoadFinished()
		adapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_list_item_1, null, fromColumns,
				toViews, 0);
		setListAdapter(adapter);

		// Initiate the Cursor Loader
		getLoaderManager().initLoader(0, null, this);
		
		lv.setOnItemClickListener(this);
		
	 	ActionBar actionBar = getActionBar();
	    actionBar.setDisplayShowTitleEnabled(false);
	    actionBar.setDisplayShowHomeEnabled(false);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.searchview_in_menu, menu);
		inflater.inflate(R.menu.main_option_menu, menu);
		MenuItem searchItem = menu.findItem(R.id.action_search);		
		mSearchView = (SearchView) searchItem.getActionView();
		setupSearchView(searchItem);
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.itmListAll:     
			Intent launchListAll = new Intent(this, MainActivity.class);			
			startActivity(launchListAll);			
			break;
		case R.id.itmHelp:    
			new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.app_name)
			.setMessage("Sổ tay nấu ăn - Nguyễn Phú Thịnh/Lê Xuân Mai").create().show();
			break;
		case R.id.itmHistory:    
			Intent launchHistory = new Intent(this, HistoryListActivity.class);			
			startActivity(launchHistory);	
			break;
		case R.id.itmFavourite:  
			Intent launchFavourite = new Intent(this, MainActivity.class);
			Bundle extras = new Bundle();
			extras.putInt(MainActivity.FAVOURITE, 1);
			launchFavourite.putExtras(extras);
			startActivity(launchFavourite);			
		}
		return true;
	}

	private void setupSearchView(MenuItem searchItem) {
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		if (searchManager != null) {
			// List<SearchableInfo> searchables
			// =searchManager.getSearchablesInGlobalSearch();
			SearchableInfo info = searchManager
					.getSearchableInfo(getComponentName());
			mSearchView.setSearchableInfo(info);
		}

		mSearchView.setIconifiedByDefault(false);
		mSearchView.setOnQueryTextListener(this);
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
	    // getIntent() should always return the most recent
	    setIntent(intent);
	    String searchQuery = getIntent().getStringExtra(SearchManager.QUERY);	  
	    Bundle bundle = getIntent().getExtras();
	    if (bundle == null)
	    	bundle = new Bundle();
	    
	    searchQuery = searchQuery == null ? "" : searchQuery;
	    bundle.putString(QUERY_EXTRA_KEY, searchQuery);
 	    performSearch(bundle);
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		Bundle bundle = getIntent().getExtras();
		if (bundle == null)
	    	bundle = new Bundle();
		bundle.putString(QUERY_EXTRA_KEY, newText); 	
		performSearch(bundle);		
		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String newText) {
		Bundle bundle = getIntent().getExtras();	
		if (bundle == null)
	    	bundle = new Bundle();
		bundle.putString(QUERY_EXTRA_KEY, newText);
		performSearch(bundle);
		return false;
	}

	public boolean onClose() {
		return false;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
		// Replace the result Cursor displayed by the Cursor Adapter with
		// the new result set.
		adapter.swapCursor(arg1);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		// Remove the existing result Cursor from the List Adapter.
		adapter.swapCursor(null);
	}

	// Execute the search.
	private void performSearch(Bundle bundle) {
		// Pass the search query as an argument to the Cursor Loader
//		Bundle args = new Bundle();
//		args.putString(QUERY_EXTRA_KEY, query);

		// Restart the Cursor Loader to execute the new query.
		getLoaderManager().restartLoader(0, bundle, this);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		String query = "";
		int favourite = 0;

		// Extract the search query from the arguments.
		if (args != null) {
			query = args.getString(QUERY_EXTRA_KEY);
			favourite = args.getInt(FAVOURITE);
		}

		// Construct the new query in the form of a Cursor Loader.
		String[] projection = { Constants.KEY_ID, Constants.FOOD_NAME };
		String where = Constants.FOOD_NAME + " like '%" + query + "%'";
		if (favourite == 1) {
			where += " and " + Constants.FOOD_FAVOURITE + " = '1'";
		}

		String[] whereArgs = new String[] {};

		String sortOrder = Constants.FOOD_NAME + " COLLATE LOCALIZED ASC";
		// Create the new Cursor loader.
		return new CursorLoader(this, FoodContentProvider.CONTENT_URI,
				projection, where, whereArgs, sortOrder);

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
		// TODO Auto-generated method stub
		Bundle bundle = new Bundle();
		bundle.putInt(DETAIL_ID,(int)id);
		
		FoodDetailActivity.startFoodDetail(MainActivity.this, view, bundle);
		
		/*Intent launchDetailFood = new Intent(MainActivity.this, FoodDetailActivity.class);
		launchDetailFood.putExtra("DETAIL_ID", id);
		launchDetailFood.putExtra("DETAIL_POS", position);
		startActivity(launchDetailFood);*/
	}
	
	


}
